package bc

import (
	"github.com/flipped-aurora/gin-vue-admin/server/global"
	"github.com/flipped-aurora/gin-vue-admin/server/model/bc"
	bcReq "github.com/flipped-aurora/gin-vue-admin/server/model/bc/request"
	"github.com/flipped-aurora/gin-vue-admin/server/model/common/request"
)

type BcChannalService struct {
}

// CreateBcChannal 创建bcChannal表记录
// Author [piexlmax](https://github.com/piexlmax)
func (bcChannalService *BcChannalService) CreateBcChannal(bcChannal *bc.BcChannal) (err error) {
	err = global.GVA_DB.Create(bcChannal).Error
	return err
}

// DeleteBcChannal 删除bcChannal表记录
// Author [piexlmax](https://github.com/piexlmax)
func (bcChannalService *BcChannalService) DeleteBcChannal(bcChannal bc.BcChannal) (err error) {
	err = global.GVA_DB.Delete(&bcChannal).Error
	return err
}

// DeleteBcChannalByIds 批量删除bcChannal表记录
// Author [piexlmax](https://github.com/piexlmax)
func (bcChannalService *BcChannalService) DeleteBcChannalByIds(ids request.IdsReq) (err error) {
	err = global.GVA_DB.Delete(&[]bc.BcChannal{}, "id in ?", ids.Ids).Error
	return err
}

// UpdateBcChannal 更新bcChannal表记录
// Author [piexlmax](https://github.com/piexlmax)
func (bcChannalService *BcChannalService) UpdateBcChannal(bcChannal bc.BcChannal) (err error) {
	bcChannal.RecordVersion = bcChannal.RecordVersion + 1
	err = global.GVA_DB.Save(&bcChannal).Where("record_version =? ", bcChannal.RecordVersion).Error
	return err
}

// GetBcChannal 根据id获取bcChannal表记录
// Author [piexlmax](https://github.com/piexlmax)
func (bcChannalService *BcChannalService) GetBcChannal(id uint) (bcChannal bc.BcChannal, err error) {
	err = global.GVA_DB.Where("id = ?", id).First(&bcChannal).Error
	return
}

func (bcChannalService *BcChannalService) GetBcChannalByProjectId(id int) (bcChannal bc.BcChannal, err error) {
	err = global.GVA_DB.Where("project_id = ?", id).First(&bcChannal).Error
	return
}

// GetBcChannalInfoList 分页获取bcChannal表记录
// Author [piexlmax](https://github.com/piexlmax)
func (bcChannalService *BcChannalService) GetBcChannalInfoList(info bcReq.BcChannalSearch) (list []bc.BcChannal, total int64, err error) {
	limit := info.PageSize
	offset := info.PageSize * (info.Page - 1)
	// 创建db
	db := global.GVA_DB.Model(&bc.BcChannal{})
	var bcChannals []bc.BcChannal
	// 如果有条件搜索 下方会自动创建搜索语句
	if info.StartCreatedAt != nil && info.EndCreatedAt != nil {
		db = db.Where("created_at BETWEEN ? AND ?", info.StartCreatedAt, info.EndCreatedAt)
	}
	err = db.Count(&total).Error
	if err != nil {
		return
	}

	if limit != 0 {
		db = db.Limit(limit).Offset(offset)
	}

	err = db.Find(&bcChannals).Error
	return bcChannals, total, err
}
